"""
pagamiago - free software script to send PayPal payments

Copyright (C) 2018 Alyssa Rosenzweig

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from pagamigo.RequestSession import RequestSession
import pagamigo.validator as Validator
import pagamigo.PeerToPeer as PeerToPeer

from lxml.html import parse
from io import StringIO

ID = "donate-button"
DESCRIPTION = "Donate from a 'donate button'"

ARGS = {
    "url": (
        "URL (copy from your browser)",
        "url",
        None),
    "amount": (
        "Amount to be transferred (1.21 for $1.21)",
        "amount",
        Validator.amount)}


# To handle donate buttons, we snarf out the donation email from the splash
# page, and then reuse the p2p money transfer infrastructure.

def flow(session, url, base, amount):
    session.set_module("", "Donate button", 5)

    portal = session.request(url[len(base):], False, {}, plain_headers=True, mock_resp = "resps/portal-donate.html")
    tree = parse(StringIO(portal)).getroot()

    email = tree.body.attrib["data-donation-email"]

    if email is None:
        print("ERROR: Unable to determine donation email. This is a pagamigo bug.")
        sys.exit(1)

    PeerToPeer.flow(session, email, amount, set_module=False)
